﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Tebbee.Business.Server;
using Tebbee.UI.Client.PublisherSer;
using Tebbee.UI.Client.UtilitiesSer;

namespace Tebbee.UI.Client.Controllers.UserApi
{
    public class PublisherController : ApiController
    {
        private readonly PublisherSerClient db = new PublisherSerClient();
        private readonly UtilitiesClient utilities = new UtilitiesClient();

        /// <summary>
        /// Api get ads by publisher id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<Advertise_GetAdvByPublisherId_Result> GetAdvByPublisherId(int id)
        {
            var queryString = HttpUtility.ParseQueryString(Request.RequestUri.Query);
            var page = Int32.Parse(queryString["page"]);
            var elementQ = Int32.Parse(queryString["elementQ"]);
            var orderBy = Int32.Parse(queryString["orderBy"]);
            if (page < 1) page = 1;
            page = (page - 1) * elementQ;
            var advs = db.GetAdvByPubId(id, page, elementQ + 1, orderBy);
            Parallel.ForEach(advs, item =>
            {
                var link = String.Empty;
                if (String.IsNullOrEmpty(item.Description))
                {
                    item.Description = "";
                }
                else
                {
                    link = item.Description.Replace("../", "");
                    var path = Path.Combine(HttpRuntime.AppDomainAppPath, link);
                    item.Description = utilities.ReadFile(path);
                }
            });
            return advs;
        }

        /// <summary>
        /// api get ads by current login publisher
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Advertise_GetPubAds_Result> GetAdvByCurrentPub()
        {
            var queryString = HttpUtility.ParseQueryString(Request.RequestUri.Query);
            var page = Int32.Parse(queryString["page"]);
            var elementQ = Int32.Parse(queryString["elementQ"]);
            var orderBy = Int32.Parse(queryString["orderBy"]);
            if (page < 1) page = 1;
            page = (page - 1) * elementQ;
            var userName = HttpContext.Current.User.Identity.Name;
            var advs = db.GetAdvByCurrentPub(userName, page, elementQ + 1, orderBy);
            Parallel.ForEach(advs, item =>
            {
                var link = String.Empty;
                if (String.IsNullOrEmpty(item.Description))
                {
                    item.Description = "";
                }
                else
                {
                    link = item.Description.Replace("../", "");
                    var path = Path.Combine(HttpRuntime.AppDomainAppPath, link);
                    item.Description = utilities.ReadFile(path);
                }
            });
            return advs;
        }

        /// <summary>
        /// api get publisher channel information by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Channel_GetByPubId_Result GetPubChannel(int id)
        {
            var channel = db.GetChanelByPubId(id);
            var link = String.Empty;
            if (String.IsNullOrEmpty(channel.About))
            {
                link = "Advertise/DefaultAssets/about.html";
            }
            else
            {
                link = channel.About.Replace("../", "");
            }
            var path = Path.Combine(HttpRuntime.AppDomainAppPath, link);
            channel.About = utilities.ReadFile(path);
            return channel;
        }

        /// <summary>
        /// api get cuurent online publisher channel information
        /// </summary>
        /// <returns></returns>
        public Channel_GetCurrentChanel_Result GetCurrentChannel()
        {
            var userName = HttpContext.Current.User.Identity.Name;
            var channel = db.GetCurrentChanel(userName);
            var link = String.Empty;
            if (String.IsNullOrEmpty(channel.About))
            {
                link = "Advertise/DefaultAssets/about.html";
            }
            else
            {
                link = channel.About.Replace("../", "");
            }
            var path = Path.Combine(HttpRuntime.AppDomainAppPath, link);
            channel.About = utilities.ReadFile(path);
            return channel;

        }

        /// <summary>
        /// Change publisher logo
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage PostLogo()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            var pubid = httpRequest.Form["pubid"];
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                for (int i = 0; i < httpRequest.Files.Count; i++)
                {
                    var postedFile = httpRequest.Files[i];
                    if (postedFile.ContentLength == 0)
                    {
                        continue;
                    }
                    var fileName = "Logo_" + pubid + "." + Path.GetExtension(postedFile.FileName);
                    var filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/PublisherLogo/" + fileName);
                    var link = String.Empty;
                    try
                    {
                        postedFile.SaveAs(filePath);
                        link = "../Advertise/PublisherLogo/" + fileName;
                        db.Channel_ChangeAvatar(Convert.ToInt32(pubid), link); 
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.Message);
                    }
                    docfiles.Add(link);
                }

                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return result;
        }

        /// <summary>
        /// Change publisher cover
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage PostCover()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            var pubid = httpRequest.Form["pubid"];
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                for (int i = 0; i < httpRequest.Files.Count; i++)
                {
                    var postedFile = httpRequest.Files[i];
                    if (postedFile.ContentLength == 0)
                    {
                        continue;
                    }
                    var fileName = "Cover_" + pubid + Path.GetExtension(postedFile.FileName);
                    var path = "../Advertise/Cover/" + fileName;
                    var filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/Cover/" + fileName);
                    try
                    {
                        postedFile.SaveAs(filePath);
                        db.Channel_ChangeCover(Convert.ToInt32(pubid), path);
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.Message);
                    }
                    docfiles.Add(path);
                }

                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return result;
        }

        /// <summary>
        /// Update publisher information
        /// </summary>
        /// <param name="pub"></param>
        /// <returns></returns>
        public HttpResponseMessage PutChannel(Publisher pub)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (db.Channel_Edit(pub) != 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, pub);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
            }
        }

        /// <summary>
        /// api get publisher followers
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Publisher_GetSubcribers_Result> GetSubcribers()
        {
            var userName = HttpContext.Current.User.Identity.Name;
            var subs = db.Channel_Subcribers(userName);
            return subs;
        }

        /// <summary>
        /// api get publisher newest comments
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Publisher_GetNewComment_Result> GetNewComments()
        {
            var userName = HttpContext.Current.User.Identity.Name;
            var comments = db.Channel_NewComments(userName);
            return comments;
        }

        /// <summary>
        /// api post gallery
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage PostGallery(int id)
        {
            var userName = HttpContext.Current.User.Identity.Name;
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                for (int i = 0; i < httpRequest.Files.Count; i++)
                {
                    var postedFile = httpRequest.Files[i];
                    if (postedFile.ContentLength == 0)
                    {
                        continue;
                    }
                    var fileName = DateTime.Now.ToString("ddMMyyyy") + DateTime.Now.Minute + Path.GetFileName(postedFile.FileName);
                    var filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/Gallery/" + fileName);
                    var link = String.Empty;
                    try
                    {
                        postedFile.SaveAs(filePath);
                        link = "../Advertise/Gallery/" + fileName;
                        db.Gallery_insert(userName, id, link);
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.Message);
                    }
                    docfiles.Add(link);
                }

                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return result;
        }

        /// <summary>
        /// Get Publisher gallery
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Gallery_GetByPub_Result> GetGallery()
        {
            var userName = HttpContext.Current.User.Identity.Name;
            var gallery = db.Gallery_GetByPub(userName);
            return gallery;
        }

        /// <summary>
        /// Get Publisher gallery by id
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Gallery_GetByPubId_Result> GetGalleryWithId(int Id)
        {
            var gallery = db.Gallery_GetByPubId(Id);
            return gallery;
        }

        /// <summary>
        /// Change publisher about
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage PutAbout(Channel channel)
        {
            var userName = HttpContext.Current.User.Identity.Name;
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            try
            {
                string fileName = String.Format("{0:ddMMyyyy}-PubliserAbout-{1}.html", DateTime.Now, userName);
                string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Advertise/html/" + fileName);
                if (utilities.WriteFile(channel.About, path)) channel.About = "../Advertise/html/" + fileName;
                else return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                db.Channel_updateAbout(userName, channel.About);
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK, channel);
        }
    }
}
